import { defineComponent } from 'vue';
import { BasicForm, useForm } from '@/components/Form';
import { BasicModal, useModalInner } from '@/components/Modal';
import { useMessage } from '@/hooks/web/useMessage';
import { getActionModalSchemas } from '../tableConfig';
import { addDutyApi, putDutyApi } from '../service';
import dayjs from 'dayjs';

export default defineComponent({
  name: 'ActionModal',
  emits: ['register', 'reload'],
  setup(_, { emit }) {
    const {
      createMessage: { success },
    } = useMessage();

    const [registerModal, { changeLoading, changeOkLoading, closeModal, setModalProps }] =
      useModalInner(async ({ record, type = 'add' }) => {
        changeLoading(true);
        changeOkLoading(true);
        setModalProps({ title: `${type === 'add' ? '新增' : '编辑'}值班安排` });
        if (type === 'edit') {
          console.log(record);
          await setFieldsValue(record || {});
        }
        changeLoading(false);
        changeOkLoading(false);
      });

    const [registerForm, { validate, setFieldsValue }] = useForm({
      labelWidth: 100,
      baseColProps: { span: 24 },
      schemas: getActionModalSchemas(),
      showActionButtonGroup: false,
    });

    const handleSubmit = async () => {
      changeLoading(true);
      changeOkLoading(true);

      try {
        const values = await validate();
        if (!values.DutyScheduleID) {
          await addDutyApi({ ...values, Date: dayjs(values.Date).format('YYYY-MM-DD') });
          success('新增成功');
        } else {
          await putDutyApi({ ...values, Date: dayjs(values.Date).format('YYYY-MM-DD') });
          success('更新成功');
        }
        closeModal();
        emit('reload');
      } finally {
        changeLoading(false);
        changeOkLoading(false);
      }
    };

    return () => (
      <BasicModal
        width={600}
        minHeight={300}
        onRegister={registerModal}
        destroyOnClose
        onOk={handleSubmit}
      >
        <div class="px-4">
          <BasicForm onRegister={registerForm} />
        </div>
      </BasicModal>
    );
  },
});
